<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js原型链之方法借用</title>
  <style>
    .red {
      background-color: red;
      color: #fff;
    }
  </style>
</head>
<body>
  <ul>
    <li>有时在对象中实现某个功能，虽然自身不存在，但可"借用"别的对象中已有的方法</li>
    <li>有时对DOM节点的操作经常会"借用"数组的某些函数来达到需求</li>
  </ul>
  <button class="red">红色按钮</button>
  <button>普通按钮</button>
  <script>
    const obj = {
      nums: [1, 2, 5, 8, 7, 6, 4, 3]
    }
    Object.setPrototypeOf(obj, {
      max(nums) {
        nums = nums || this.nums
        return nums.sort((a, b) => b - a)[0]
      },
    })
    console.log(obj.max())               // 8
    console.log(obj.max(obj.nums))       // 8
    const web = {
      blogs: { 'js': 10, 'ts': 50, 'es': 20, 'css': 36, 'html': 48 },
      // getter
      get nums() {
        return Object.values(this.blogs)
      }
    }
    console.log(obj.max.apply(web))                               // 50
    console.log(obj.max.call(null, Object.values(web.blogs)))     // 50
    // 可利用Math.max优化
    console.log(Math.max.apply(null, obj.nums))                   // 8
    console.log(Math.max.apply(null, Object.values(web.blogs)))   // 50
    console.log(Math.max.call(null, ...obj.nums))                 // 8
    console.log(Math.max.call(null, ...Object.values(web.blogs))) // 50
    // DOM节点筛选
    const btns = document.querySelectorAll('button')
    // const filterBtns = Array.prototype.filter.call(btns, item => item.hasAttribute('class'))
    const filterBtns = [].filter.call(btns, item => item.hasAttribute('class'))
    console.log(btns)
    console.log(filterBtns)
  </script>
</body>
</html>